const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 点赞评论
  async likeReview(userId, reviewId) {
    // 检查评论是否存在
    const [reviews] = await db.execute(
      'SELECT id FROM reviews WHERE id = ?',
      [reviewId]
    );
    
    if (reviews.length === 0) {
      throw new Error('评论不存在');
    }
    
    // 检查是否已点赞
    const [existing] = await db.execute(
      'SELECT id FROM likes WHERE user_id = ? AND review_id = ?',
      [userId, reviewId]
    );
    
    if (existing.length > 0) {
      throw new Error('已点赞过此评论');
    }
    
    const [result] = await db.execute(
      'INSERT INTO likes (user_id, review_id) VALUES (?, ?)',
      [userId, reviewId]
    );
    
    return result.affectedRows > 0;
  },

  // 取消点赞
  async unlikeReview(userId, reviewId) {
    const [result] = await db.execute(
      'DELETE FROM likes WHERE user_id = ? AND review_id = ?',
      [userId, reviewId]
    );
    
    if (result.affectedRows === 0) {
      throw new Error('点赞不存在');
    }
    
    return true;
  },

  // 检查是否已点赞
  async checkLike(userId, reviewId) {
    const [likes] = await db.execute(
      'SELECT id FROM likes WHERE user_id = ? AND review_id = ?',
      [userId, reviewId]
    );
    
    return likes.length > 0;
  }
};